package com.hhm.huo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhm.huo.entity.Authority;
import com.hhm.huo.entity.User;
import com.hhm.huo.mapper.AuthorityMapper;
import com.hhm.huo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户详情接口实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    AuthorityMapper authorityMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 用户 -- 账号、密码
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        if (user==null){
            throw new UsernameNotFoundException("用户："+ username + "不存在");
        }

        // 查看该用户权限
        QueryWrapper<Authority> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("username", username);
        List<Authority> authorities = authorityMapper.selectList(wrapper1);
        for (Authority authority : authorities) {
            if ("ADMIN".equals(authority.getAuthority())){
                user.setAdmin(1);
            }
        }
        return user;
    }
}
